/*
 * @Author: humengchuan 531537052@qq.com
 * @Date: 2024-12-26 09:35:05
 * @LastEditors: humengchuan 531537052@qq.com
 * @LastEditTime: 2024-12-26 11:25:22
 * @FilePath: \projecte:\学习\react\react-optimize-ts\src\utils\baseApi.ts
 * @Description: 
 */
// src/utils/baseApi.ts

const BASE_URL = 'https://api.example.com'; // 替换为你的API基础URL

interface RequestOptions {
  headers?: Record<string, string>;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
  body?: any;
  token?: string;
  [key: string]: any; // 允许其他属性
}

const baseApi = async (endpoint: string, options: RequestOptions = {}): Promise<any> => {
  const headers:  Record<string, string> = {
    ...options.headers,
  };
  
  // 如果 headers 中没有设置 Content-Type，则使用默认的 'application/json'
  if (!headers['Content-Type']) {
    headers['Content-Type'] = 'application/json';
  }
  // 如果有token，添加到请求头中
  // if (options.token) {
  //   headers['Authorization'] = `Bearer ${options.token}`;
  // }
  const response = await fetch(`${BASE_URL}${endpoint}`, {
    ...options,
    headers,
  });

  if (!response.ok) {
    const errorData = await response.json();
    throw new Error(errorData.message || `HTTP error! Status: ${response.status}`);
  }

  return response.json();
};

export default baseApi;